package com.thhgh.utils;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author Zhikang.Peng
 * @version 1.0
 * @email thghh@qq.com
 * @date 2021/6/24 10:27
 */
@Component
@Aspect
public class LogUtil {

    @Pointcut("execution(public * com.thhgh.service.TransferService.updateAccountByCardNo(com.thhgh.pojo.Account))")
    public void pointcut() {
        System.out.println("pointcut");
    }

    @Before("pointcut()")
    public void beforePrintLog(JoinPoint jp) {
        Object[] args = jp.getArgs();
        System.out.println("前置通知: beforePrintLog, 参数:" + Arrays.toString(args));
    }

    @AfterThrowing(value = "pointcut()", throwing = "e")
    public void afterThrowingPrintLog(Throwable e) {
        System.out.println("异常通知: beforePrintLog, 参数:" + e);
    }

    @After("pointcut()")
    public void afterPrintLog() {
        System.out.println("最终通知： afterPrintLog");
    }

    @Around("pointcut()")
    public Object aroundPrintLog(ProceedingJoinPoint pjp) {
        //定义返回值
        Object rtValue = null;
        try {
            //前置通知
            System.out.println("前置通知");
            //1.获取参数
            Object[] args = pjp.getArgs();
            //2.执⾏切⼊点⽅法
            rtValue = pjp.proceed(args);
            //后置通知
            System.out.println("后置通知");
        } catch (Throwable t) {
            //异常通知
            System.out.println("异常通知");
            t.printStackTrace();
        } finally {
            //最终通知
            System.out.println("最终通知");
        }
        return rtValue;
    }

}
